package com.okhttp.interceptor;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;

/**
 * @author YLG
 * @Datetime 2020/4/22-10:11 PM
 * @Version v1.0
 * @description 统一主求头信息
 */
public class HeaderInterceptor implements Interceptor {
  
  private Map<String,String> headers;
  public HeaderInterceptor(Map<String,String> headers){
    this.headers=headers;
  }

  @NotNull
  @Override
  public Response intercept(@NotNull Chain chain) throws IOException {
    // clone 一个Request,然后添加Header
    if(headers!=null){
      Request.Builder builder = chain.request().newBuilder();
      for (Entry<String, String> entry : headers.entrySet()) {
        builder.addHeader(entry.getKey(),entry.getValue());
      }
      return chain.proceed(builder.build());
    }else {
      return chain.proceed(chain.request());
    }
  }
}
